package com.zzx.business.controller;

import com.zzx.business.service.ITbNodesService;
import com.zzx.business.vo.TbNodesVo;
import com.zzx.common.annotation.Log;
import com.zzx.common.core.controller.BaseController;
import com.zzx.common.core.domain.AjaxResult;
import com.zzx.common.core.page.TableDataInfo;
import com.zzx.common.enums.BusinessType;
import com.zzx.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 项目节点Controller
 *
 * @author Zzx
 * @date 2025-05-23
 */
@Api(tags = "项目节点Controller")
@RestController
@RequestMapping("/business/nodes")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TbNodesController extends BaseController {

    private final ITbNodesService tbNodesService;

    @ApiOperation("查询项目节点列表")
    @PreAuthorize("@ss.hasPermi('business:nodes:list')")
    @GetMapping("/list")
    public TableDataInfo<TbNodesVo> list(TbNodesVo entity) {
        return tbNodesService.queryList(entity);
    }

    @ApiOperation("查询项目节点所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(TbNodesVo entity) {
        List<TbNodesVo> tbNodesVos = tbNodesService.queryAll(entity);
        if(!tbNodesVos.isEmpty()){
            for (TbNodesVo tbNodesVo : tbNodesVos) {
                Long from = tbNodesVo.getFrom();
                if(from == 0){
                    List<TbNodesVo> tbNodesVos1 = sortTbNodes(tbNodesVos, tbNodesVo);
                    return AjaxResult.success("查询成功", tbNodesVos1);
                }
            }
        }
        return AjaxResult.success("查询成功", new ArrayList<>());
    }

    @ApiOperation("导出项目节点列表")
    @PreAuthorize("@ss.hasPermi('business:nodes:export')")
    @Log(title = "项目节点", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbNodesVo entity) {
        List<TbNodesVo> list = tbNodesService.queryAll(entity);
        ExcelUtil<TbNodesVo> util = new ExcelUtil<>(TbNodesVo.class);
        util.exportExcel(response, list, "项目节点数据");
    }

    @ApiOperation("获取项目节点详细信息")
    @PreAuthorize("@ss.hasPermi('business:nodes:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success("查询成功", tbNodesService.queryById(id));
    }

    @ApiOperation("新增项目节点")
    @PreAuthorize("@ss.hasPermi('business:nodes:add')")
    @Log(title = "项目节点", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody TbNodesVo entity) {
        return toAjax(tbNodesService.saveNode(entity));
    }

    @ApiOperation("修改项目节点")
    @PreAuthorize("@ss.hasPermi('business:nodes:edit')")
    @Log(title = "项目节点", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody TbNodesVo entity) {
        return toAjax(tbNodesService.updateById(entity));
    }

    @ApiOperation("删除项目节点")
    @PreAuthorize("@ss.hasPermi('business:nodes:remove')")
    @Log(title = "项目节点", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tbNodesService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }



    public static List<TbNodesVo> sortTbNodes(List<TbNodesVo> edges, TbNodesVo startNode) {
        Map<Long, TbNodesVo> edgeMap = new HashMap<>();
        for (TbNodesVo edge : edges) {
//            if (edgeMap.containsKey(edge.getFrom())) {
//                throw new IllegalArgumentException("存在重复的起始ID: " + edge.getFrom());
//            }
            edgeMap.put(edge.getId(), edge);
        }

        List<TbNodesVo> sortedList = new ArrayList<>();
        Long currentId = startNode.getId();
        while (currentId != null) {
            TbNodesVo currentEdge = edgeMap.get(currentId);
            if (currentEdge == null) break;
            sortedList.add(currentEdge);
            if( currentEdge.getTo() == 0l){
                break;
            }
            currentId = currentEdge.getTo();
            // 检测循环或超出预期长度
            if (sortedList.size() > edges.size()) {
                throw new IllegalArgumentException("检测到循环或无效链");
            }
        }

//        if (sortedList.size() != edges.size()) {
//            throw new IllegalArgumentException("无法形成完整链式结构");
//        }
        return sortedList;
    }

    public static List<TbNodesVo> sortTbNodes(List<TbNodesVo> edges, Long startId) {
        Map<Long, TbNodesVo> edgeMap = new HashMap<>();
        for (TbNodesVo edge : edges) {
            if (edgeMap.containsKey(edge.getFrom())) {
                throw new IllegalArgumentException("存在重复的起始ID: " + edge.getFrom());
            }
            edgeMap.put(edge.getFrom(), edge);
        }

        List<TbNodesVo> sortedList = new ArrayList<>();
        Long currentId = startId;

        while (currentId != null) {
            TbNodesVo currentEdge = edgeMap.get(currentId);
            if (currentEdge == null) break;
            sortedList.add(currentEdge);
            currentId = currentEdge.getTo();

            // 检测循环或超出预期长度
            if (sortedList.size() > edges.size()) {
                throw new IllegalArgumentException("检测到循环或无效链");
            }
        }
        if (sortedList.size() != edges.size()) {
            throw new IllegalArgumentException("无法形成完整链式结构");
        }
        return sortedList;
    }
}
